import util.ListNode;


/**
 * 执行用时：2 ms, 在所有 Java 提交中击败了99.37% 的用户
 * 内存消耗：38.6 MB, 在所有 Java 提交中击败了68.50% 的用户
 *
 * 加法
 * 末位计算是否加1位
 */
public class AddTwoNumbersSec {

    public static void main(String[] args) {
        AddTwoNumbersUtil.init();
        ListNode res = addTwoNumbers(AddTwoNumbersUtil.getN1(), AddTwoNumbersUtil.getN1());

        System.out.println(res);

    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null, tail = null;
        int n1, n2, carry = 0, sum;
        // 依次取值，相加
        while (l1 != null || l2 != null) {
            n1 = l1 == null ? 0 : l1.val;
            n2 = l2 == null ? 0 : l2.val;
            sum = n1 + n2 + carry;
            if (head == null) {
                head = tail = new ListNode(sum % 10);
            }else{
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
            }
            carry = sum /10;
//            res.val = sum;
//            res.next = new ListNode();
//            res = res.next;

            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        }
        if (carry > 0){
            tail.next = new ListNode(carry);
        }
        return head;
    }

}
